package com.sikaryofficial.backend.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sikaryofficial.backend.annotation.Repeat;
import com.sikaryofficial.backend.annotation.TenantFilter;
import com.sikaryofficial.backend.config.TenantFilterProperties;
import com.sikaryofficial.backend.constant.ActivityTypeEnum;
import com.sikaryofficial.backend.domain.dto.SysDictDataDTO;
import com.sikaryofficial.backend.domain.dto.req.productactivity.ActivityDeleteReq;
import com.sikaryofficial.backend.domain.dto.req.productactivity.ActivityListReq;
import com.sikaryofficial.backend.domain.dto.req.productactivity.ActivityReq;
import com.sikaryofficial.backend.domain.dto.req.productactivity.ActivityResultListReq;
import com.sikaryofficial.backend.domain.dto.resp.productactivity.ActivityDTO;
import com.sikaryofficial.backend.domain.dto.resp.productactivity.ActivityResultNoMaskDTO;
import com.sikaryofficial.backend.domain.vo.BrandTenantVO;
import com.sikaryofficial.backend.domain.vo.export.ActivityExportVO;
import com.sikaryofficial.backend.manager.ActivityManager;
import com.sikaryofficial.common.core.domain.R;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.common.core.utils.PageUtil;
import com.sikaryofficial.common.core.web.controller.BaseController;
import com.sikaryofficial.common.core.web.domain.PageResult;
import com.sikaryofficial.common.log.annotation.Log;
import com.sikaryofficial.common.log.enums.BusinessType;
import com.sikaryofficial.common.security.annotation.RequiresPermissions;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 活动Controller
 *
 * @author qinjinyuan
 * @date 2023-10-27
 */
@RestController
@RequestMapping("/activity/build")
@Api(tags = "V3.5-活动后台管理")
@Slf4j
public class ActivityBuildController extends BaseController {
    @Autowired
    private ActivityManager activityManager;
    @Value("${hismk.activity.export.name:ske_activity_}")
    private String exportFileName;
    @Resource
    private TenantFilterProperties tenantFilterProperties;

    /**
     * 获奖名单
     */
    @RequiresPermissions("activity:awards:list")
    @PostMapping("/awardsListPage")
    @ApiOperation("获奖名单(活动管理)")
    @TenantFilter
    public PageResult<ActivityResultNoMaskDTO> awardsListPage(@Validated @RequestBody ActivityResultListReq req) {
        // 查询获奖列表
        IPage<ActivityResultNoMaskDTO> page = activityManager.publishAwardsNoMaskList(req);
        return PageUtil.success(page.getRecords(), page.getTotal());
    }

    /**
     * 活动导出
     *
     * @param response
     * @param req
     * @throws Exception
     */
    @PostMapping("/export")
    @ApiOperation(value = "活动导出")
    @TenantFilter
    public void activityExport(HttpServletResponse response, @RequestBody ActivityDeleteReq req) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            String fileName = exportFileName + LocalDateTimeUtil.format(LocalDateTime.now(), DateTimeFormatter.ofPattern(DatePattern.PURE_DATETIME_FORMAT.getPattern()));
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcelFactory.write(response.getOutputStream(), ActivityExportVO.class).sheet("ske_activity").doWrite(activityManager.activityExport(req));
        } catch (Exception e) {
            log.error("activityExport:{}", e);
            throw new ServiceException("activity export error.");
        }
    }

    /**
     * 后台管理-活动类型
     */
    @PostMapping("/getActivityType")
    @ApiOperation("活动类型")
    public R<List<SysDictDataDTO>> getActivityType() {
        ActivityTypeEnum[] reportTypeEnums = ActivityTypeEnum.values();
        List<SysDictDataDTO> result = new ArrayList<>();
        for (ActivityTypeEnum reportTypeEnum : reportTypeEnums) {
            // 暂不支持这种类型
            if(reportTypeEnum == ActivityTypeEnum.PURCHASE_ACTIVATE_NOW){
                continue;
            }
            SysDictDataDTO sysDictDataDTO = new SysDictDataDTO();
            result.add(sysDictDataDTO);
            sysDictDataDTO.setDictDesc(reportTypeEnum.getName());
            sysDictDataDTO.setDictDesc(reportTypeEnum.getDesc());
            sysDictDataDTO.setDictValue(reportTypeEnum.getCode() + "");
            sysDictDataDTO.setDictType("activity_type");
        }
        return R.ok(result);
    }

    @GetMapping("/brandPlatform")
    @ApiOperation("后台管理-子品牌列表")
    public R<List<SysDictDataDTO>> brandPlatform() {
        List<BrandTenantVO> brandTenantList = tenantFilterProperties.getBrandTenantList();
        List<SysDictDataDTO> result = new ArrayList<>();
        for (BrandTenantVO brandTenantVO : brandTenantList) {
            SysDictDataDTO sysDictDataDTO = new SysDictDataDTO();
            result.add(sysDictDataDTO);
            sysDictDataDTO.setDictLabel(brandTenantVO.getBrandNo());
            sysDictDataDTO.setDictDesc(brandTenantVO.getBrandNo());
            sysDictDataDTO.setDictValue(brandTenantVO.getTenantId() + "");
            sysDictDataDTO.setDictType("brand_platform");
        }
        return R.ok(result);
    }

    /**
     * 后台管理-活动列表
     */
    @PostMapping("/listPage")
    @ApiOperation("后台管理-活动列表")
    @TenantFilter
    public PageResult<ActivityDTO> listPage(@Validated @RequestBody ActivityListReq req) {
        IPage<ActivityDTO> page = activityManager.activityList(req);
        return PageUtil.success(page.getRecords(), page.getTotal());
    }

    /**
     * 后台管理-活动添加
     */
    @Log(title = "后台管理-活动基本信息保存", businessType = BusinessType.INSERT)
    @PostMapping("/save")
    @ApiOperation("V3.5-后台管理-活动基本信息保存")
    @TenantFilter
    public R<Long> save(@Validated @RequestBody ActivityReq req) {
        return R.ok(activityManager.activitySave(req));
    }

    /**
     * 后台管理-活动详情
     */
    @GetMapping("/detail/{activityId}")
    @ApiOperation("V3.5-活动详情(H5端和后端共用)")
    @Repeat
    @TenantFilter
    public R<ActivityDTO> detail(@PathVariable("activityId") Long activityId) {
        return R.ok(activityManager.detail(activityId));
    }

    /**
     * 后台管理-活动上下架
     */
    @Log(title = "后台管理-活动上下架", businessType = BusinessType.UPDATE)
    @PutMapping("/{activityId}/{opt}")
    @ApiOperation("后台管理-活动上下架")
    @TenantFilter
    public R<Boolean> activityEffect(
            @ApiParam(value = "活动ID", required = true) @PathVariable("activityId") Long activityId,
            @ApiParam(value = "0-上架;1-下架", required = true) @PathVariable("opt") Integer opt) {
        return R.ok(activityManager.activityEffect(activityId, opt));
    }

    /**
     * 后台管理-隐藏活动设置
     */
    @Log(title = "后台管理-隐藏活动设置", businessType = BusinessType.UPDATE)
    @GetMapping("/hide/{activityId}/{hide}")
    @ApiOperation("V3.5-后台管理-隐藏活动设置")
    @TenantFilter
    public R<Boolean> activityHidden(
            @ApiParam(value = "活动ID", required = true) @PathVariable("activityId") Long activityId,
            @ApiParam(value = "是否隐藏活动 0-显示 1-隐藏，默认0-显示", required = true) @PathVariable("hide") Integer hide) {
        return R.ok(activityManager.activityHidden(activityId, hide));
    }

    /**
     * 后台管理-活动删除
     */
    @Log(title = "后台管理-活动删除", businessType = BusinessType.DELETE)
    @PostMapping
    @ApiOperation("V3.5-后台管理-活动删除")
    @TenantFilter
    public R<Boolean> deleteActivity(@RequestBody ActivityDeleteReq req) {
        return R.ok(activityManager.deleteActivity(req));
    }

}
